<?php


namespace app\community;

use Jenssegers\Agent\Agent;

class UserAgent
{
    /**
     * 获取前端用户环境
     * @param ?string $user_agent
     * @return array
     */
    public function Get_User_Surroundings(?string $user_agent = null) : array
    {
        $agent = new Agent();
        $ip = request() -> ip();
        $ip_address = $ip ? (new IpUtil()) -> get_ipv4_find_map($ip) : null;
        $_SERVER['HTTP_USER_AGENT'] = request() -> getHeader('user_agent', "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36");
        $agent->setUserAgent($user_agent ? $user_agent : $_SERVER['HTTP_USER_AGENT']);
        // 语言
        $languages = $agent->languages();
        // 获取浏览器版本
        $browser = $agent->browser();
        $chrome_version = $agent->version($browser);
        // 获取系统版本
        $platform = $agent->platform();
        $os_version = $agent->version($platform);

        return [
            'chrome' => $agent->browser().$chrome_version,
            'ip' => $ip,
            'ip_address' => $ip_address ? "${ip_address['country_name']}/${ip_address['region_name']}/${ip_address['city_name']}" : "未知地址",
            'os' => $agent->platform().''.$os_version,
            'languages' => json_encode($languages, JSON_UNESCAPED_UNICODE),
            'isRobot' => $agent->isRobot(),
            'device' => $agent->device()
        ];
    }
}